import React, { useState, useEffect, } from 'react';
import './scss/RecordTable.scss'; // 样式文件
import { LgButton, LgInput, LgTextarea, lgAlert } from 'lancoo-web-ui';
import moment from 'moment';
import {
    getData,
    getRealPath,
    getQueryVariable,
    putData1,
    delData,
    postData,
    putData,
} from "../../common/js/fetch";
import { message } from "antd";
import { Scrollbars } from "react-custom-scrollbars";

const RecordTable = (props) => {
    console.log(props, 'props');
    let {
        haveTop,
        headerName,
        openPop,
        weekSheetDetail,
        selectTime,
        recordInfoDetail,
        haveSubmit,
        viewportHeight,
        closePop,
        alertPersonEdit,
        recordExport,
    } = props
    const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    const termInfo = JSON.parse(sessionStorage.getItem("termInfo"));
    let tableList = weekSheetDetail?.recordItemList, remarkValue = weekSheetDetail?.remark || '';
    const [remark, setRemark] = useState('');
    // 添加条件检查，确保 tableList 存在并且是一个数组
    const initialContents = tableList ? Array(tableList.length).fill('') : [];
    const [contents, setContents] = useState(initialContents);
    useEffect(() => {
        let contentArr = contents.concat([]);
        tableList && tableList.forEach((item, index) => {
            contentArr[index] = item?.record || ''
        })
        setRemark(remarkValue);
        setContents(contentArr);
    }, [tableList])
    // console.log(contents, 'contents');
    // Handler for input change
    const handleContentChange = (e, idx) => {
        if (weekSheetDetail?.submitStatus === '1') return;
        const newContents = [...contents];
        newContents[idx] = e.currentTarget.value;
        setContents(newContents);
    };

    const alertAQuestion = (typeId, innerTypeId) => {
        let alert = lgAlert.show({
            duration: 0,
            content: '确定要提交吗？',
            description: '点击"确定"提交记录后将不可再操作！',
            isShowCloseBtn: true,
            tipType: 'warning',
            // tipSize: 'small',
            tipSize: 'big',
            tipMouldType: 'A',
            confirmText: "确定",
            closeText: "再想想",
            showCover: true,
            coverZIndex: 1000,
            coverOpacity: 0.25,
            position: { xAxis: '50%', yAxis: '35%', showDirection: 'center', xOffset: '-50%' },
            onConfirm: () => {
                submitRecordInfo();
                lgAlert.close(alert.index);
            }
        });

    }

    // 保存记录
    const saveRecordInfo = () => {
        let recordItemList = weekSheetDetail?.recordItemList.concat([]);
        recordItemList.forEach((item, index) => {
            item.record = contents[index];
        });
        console.log(recordItemList, 'recordItemList');
        postData("/api/dw/v2/recordInfo/save", {
            recordId: weekSheetDetail?.recordId,
            recordItemList,
            remark,
            schoolId: userInfo.schoolId,
            semester: termInfo.term,
        })
            .then((data) => {
                return data.json();
            })
            .then((json) => {
                if (json.code == "200") {
                    message.success("暂存成功~");
                    if (closePop) {
                        closePop();
                    }
                } else {
                    message.error(json.msg, 3);
                }
            });
    };

    // 提交记录
    const submitRecordInfo = () => {
        let recordItemList = weekSheetDetail?.recordItemList.concat([]);
        recordItemList.forEach((item, index) => {
            item.record = contents[index];
        });
        console.log(recordItemList, 'recordItemList');
        postData("/api/dw/v2/recordInfo/submit", {
            recordId: weekSheetDetail?.recordId,
            recordItemList,
            remark,
            schoolId: userInfo.schoolId,
            semester: termInfo.term,
        })
            .then((data) => {
                return data.json();
            })
            .then((json) => {
                if (json.code == "200") {
                    message.success("提交成功~");
                    if (closePop) {
                        closePop();
                    } else {
                        recordInfoDetail(weekSheetDetail?.recordId, selectTime);
                    }
                } else {
                    message.error(json.msg, 3);
                }
            });
    };

    return (
        <div className="record_table_container">
            {
                haveTop ?
                    <div className='record_table_name'>{headerName}{haveSubmit ? <LgButton type='info' onClick={() => alertPersonEdit()} shapeType='text' className='submit_btn'>提交给校领导查看</LgButton> : ''}</div>
                    : ''
            }
            <Scrollbars
                autoHeight
                autoHide
                autoHideTimeout={100}
                style={{
                    height: haveSubmit ? 417 : tableList && tableList.length > 12 ? viewportHeight + 100 : viewportHeight - 90,
                    minHeight: haveSubmit ? 417 : tableList && tableList.length > 12 ? viewportHeight + 100 : viewportHeight - 90,
                }}
                autoHeightMin={"100%"}
            >
                <div className='table_div'>
                    <div className='table_left'>
                        {
                            tableList && tableList.map((item, index) => {
                                let userNames = (item.personList && item.personList.map(item => item.userName)) || [];
                                let grouper = userNames.join('、');

                                return (
                                    <div className='table_left_div' key={index}>
                                        <div className='table_content'>{item.content}</div>
                                        <div className='table_detail'>
                                            {
                                                haveTop && item.beQuestions === '1' && weekSheetDetail?.recordId ?
                                                    <LgInput
                                                        className="content_input"
                                                        maxLength={30}
                                                        value={contents[index]}  // Use separate content for each input
                                                        onChange={(e) => handleContentChange(e, index)}  // Pass index to identify which input is changing
                                                    />
                                                    :
                                                    item.content === '时间' && haveTop ?
                                                        <span>{weekSheetDetail?.recordTime ? moment(weekSheetDetail?.recordTime).format('YYYY-MM-DD') : selectTime ? moment(selectTime).format('YYYY-MM-DD') : ''}</span>
                                                        : (item.content === '值周老师' || item.content === '值日老师') && haveTop ? <span>{grouper ? grouper : <span style={{ color: '#999' }}></span>}</span>
                                                            : haveTop ? <span style={{ color: '#999' }}></span> : ''
                                            }
                                        </div>
                                    </div>
                                );
                            })
                        }

                        {
                            !haveTop ?
                                <div className='table_left_div'>
                                    <div className='table_detail'> <LgButton onClick={openPop} type='info' shapeType='text'>添加记录事项</LgButton></div>
                                </div>
                                : ''
                        }
                    </div>
                    <div className='table_right'>
                        <div className='table_right_remark'>备注</div>
                        <div className='remark_div'>
                            {
                                haveTop ?
                                    <LgTextarea
                                        // numberOfWords
                                        className="textarea_warp"
                                        value={remark}
                                        placeholder={'暂无备注'}
                                        textarea={{
                                            maxLength: 200,
                                            onInput: (e) => {
                                                setRemark(e.currentTarget.value)
                                            },
                                        }}
                                        currentTextQuantity={remark.length}
                                    />
                                    : ''
                            }
                        </div>
                    </div>
                </div>
            </Scrollbars>
            <div className="record_query_btn">
                {
                    weekSheetDetail?.recordId ?
                        <LgButton backgroundType="transparent" border type="info" onClick={() => recordExport()}>
                            导出
                        </LgButton>
                        : ''
                }
                {
                    weekSheetDetail?.recordId && weekSheetDetail.submitStatus !== '1' ?
                        <LgButton
                            className="storage_btn"
                            backgroundType="opacification"
                            gradient
                            type="info"
                            onClick={() => saveRecordInfo()}
                        >
                            暂存
                        </LgButton>
                        : ''
                }
                {
                    weekSheetDetail?.recordId && weekSheetDetail.submitStatus !== '1' ?
                        <LgButton backgroundType="opacification" type="success" onClick={() => alertAQuestion()}>
                            提交
                        </LgButton>
                        : ''}
            </div>
        </div>
    );
};

export default RecordTable;
